//
//  XOWMRequest.m
//  sigleAPP
//
//  Created by SKL on 2017/11/15.
//  Copyright © 2017年 SKL. All rights reserved.
//
#import "XOWMRequest.h"
@interface XOWMRequest()
@property (nonatomic, strong) NSMutableDictionary *para;
@property (nonatomic, strong) NSMutableData *data;

@end
@implementation XOWMRequest
- (NSMutableDictionary *)para
{
    if (!_para)
    {
        _para = [NSMutableDictionary dictionaryWithDictionary:helperManager().getPara().localInfo];
    }
    return _para;
}

- (NSMutableData *)data
{
    if (!_data)
    {
        _data = [NSMutableData data];
    }
    return _data;
}

- (void)yjd_registerRequst:(NSDictionary *)dict
{
    self.type = YJDRequestTypeRegister;
    [self.para setValue:[dict valueForKey:@"name"] forKey:@"account"];
    [self.para setValue:[[dict valueForKey:@"password"] yjd_md5] forKey:@"pass"];
    [self yjd_request];
}

- (void)yjd_loginRequest:(NSDictionary *)dict
{
    self.type = YJDRequestTypeLogin;
    [self.para setValue:[dict valueForKey:@"name"] forKey:@"account"];
    [self.para setValue:[[dict valueForKey:@"password"] yjd_md5] forKey:@"pass"];
    [self yjd_request];
}

- (void)yjd_authenticateRequest:(NSDictionary *)dict;
{
    self.type = YJDRequestTypeAuthenticate;
    [self.para removeAllObjects];
    [self.para setDictionary:dict];
    [self.para setValue:helperManager().getPara().accountID forKey:@"accountid"];
    [self.para setValue:helperManager().getPara().appID forKey:@"appid"];
    [self yjd_request];
}

- (void)yjd_verifyCodeRequest:(NSDictionary *)dict
{
    self.type = YJDRequestTypeVerifyCode;
    [self.para removeAllObjects];
    [self.para setDictionary:dict];
    [self.para setValue:helperManager().getPara().appID forKey:@"appid"];
    [self yjd_request];
}

- (void)yjd_findPWDRequest:(NSDictionary *)dict
{
    self.type = YJDRequestTypeFinePWD;
    [self.para setValue:[dict valueForKey:@"name"] forKey:@"account"];
    [self.para setValue:[[dict valueForKey:@"password"] yjd_md5] forKey:@"password"];
    [self yjd_request];
}

- (void)yjd_resetPWDRequest:(NSDictionary *)dict
{
    self.type = YJDRequestTypeResetPWD;
    [self.para setValue:helperManager().getPara().accountID forKey:@"accountid"];
    [self.para setValue:[[dict valueForKey:@"oldpassword"] yjd_md5] forKey:@"oldpassword"];
    [self.para setValue:[[dict valueForKey:@"password"] yjd_md5] forKey:@"password"];
    [self yjd_request];
}

- (void)yjd_bindRequest:(NSDictionary *)dict account:(NSString *)account
{
    self.type = YJDRequestTypeBind;
    [self.para removeAllObjects];
    [self.para setDictionary:dict];
    [self.para setValue:helperManager().getPara().appID forKey:@"appid"];
    if (account)
        [self.para setValue:account forKey:@"accountid"];
    else
        [self.para setValue:helperManager().getPara().accountID forKey:@"accountid"];
    [self yjd_request];
}

- (void)yjd_preparezf:(XOWMProductPara)product
{
    self.type = YJDRequestTypePrepareZF;
    [self.para insertDict:propertyDic(product)];
    [self yjd_request];
}

- (void)yjd_request
{
    NSMutableDictionary *requestPara = [NSMutableDictionary dictionary];
    
    NSString *paraString = [self.para yjd_json];
    
    [requestPara setValue:paraString forKey:@"transdata"];
    NSString *sign = [paraString yjd_sign];
    [requestPara setValue:sign forKey:@"sign"];
    [requestPara setValue:@"RSA" forKey:@"signtype"];
    [self.task cancel];
    if (self.type == YJDRequestTypeLogin)
    {
        self.task = [XOWMHttps post:LOGIN_API parameters:requestPara delegate:self];
    }
    else if (self.type == YJDRequestTypeRegister || self.type == YJDRequestTypeQuickRegister)
    {
        self.task = [XOWMHttps post:REGISTE_API parameters:requestPara delegate:self];
    }
    else if (self.type == YJDRequestTypeAuthenticate)
    {
        self.task = [XOWMHttps post:AUTHENTICATE_API parameters:requestPara delegate:self];
    }
    else if (self.type == YJDRequestTypeVerifyCode)
    {
        self.task = [XOWMHttps post:VERIFYCODE_API parameters:requestPara delegate:self];
    }
    else if (self.type == YJDRequestTypeFinePWD)
    {
        self.task = [XOWMHttps post:FORGETPASSWORD_API parameters:requestPara delegate:self];
    }
    else if (self.type == YJDRequestTypeResetPWD)
    {
        self.task = [XOWMHttps post:RESETPASSWORD_API parameters:requestPara delegate:self];
    }
    else if (self.type == YJDRequestTypeBind)
    {
        self.task = [XOWMHttps post:BIND_API parameters:requestPara delegate:self];
    }
    else if (self.type == YJDRequestTypePrepareZF)
    {
        self.task = [XOWMHttps post:PREPARE_ZF_API parameters:requestPara delegate:self];
    }
}

#pragma mark - NSURLSessionDataDelegate method
//接受到服务器响应
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
    //允许服务器回传数据
    completionHandler(NSURLSessionResponseAllow);
    
}
//接受服务器回传的数据可能执行多次
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
        [self.data appendData:data];
}

//请求成功或者失败
-(void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(NSError *)error
{
    
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
didCompleteWithError:(nullable NSError *)error
{
    if (error && (error.code != -999 || ![error.localizedDescription isEqualToString:@"cancelled"]))
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (self.delegate && [self.delegate respondsToSelector:@selector(yjd_didRequestWithReceiveData:)])
            {
                [self.delegate yjd_didRequestWithReceiveData:nil];
            }
            //            [CCAlert showMessage:[NSString stringWithFormat:@"code:%d\ninfo:%@",error.code,error.localizedDescription] hidden:nil];
            [CCAlert showMessage:[NSString stringWithFormat:@"%@",error.localizedDescription] hidden:nil];
        });
        return;
    }
    NSError *error2;
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:self.data options:NSJSONReadingMutableLeaves error:&error2];
    if (dict)
    {
        NSString *sign = [dict valueForKey:@"sign"];
        NSString *transdata = [dict valueForKey:@"transdata"];
        BOOL isSuccess = [transdata yjd_verifySign:sign];
        if (self.delegate && [self.delegate respondsToSelector:@selector(yjd_didRequestWithReceiveData:)])
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (isSuccess)
                {
                    NSDictionary *trans = [NSJSONSerialization JSONObjectWithData:[transdata dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
                    [self.delegate yjd_didRequestWithReceiveData:trans];
                }
                else
                {
                    [self.delegate yjd_didRequestWithReceiveData:nil];
                }
            });
        }
    }
    else
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            [CCHud stopHud];
            [CCAlert showMessage:@"参数错误" hidden:nil];
        });
    }
    
    self.data = nil;
    //不把本次session Invalidate,那么session持有的delegate不会被释放.
    [session finishTasksAndInvalidate];
}
- (void)dealloc
{
    [self.task cancel];
    self.task = nil;
}

@end
